import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image, Text, RichText, Swiper, SwiperItem } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import GoodsItem from '../components/goods-item'
import parse from 'mini-html-parser2'
import {
  getCheapView,
  getpMobileInfo
} from '@/api/cheap'
import { updateShareLog, updateViewLog } from '@/api/distribution'
import './index.scss'

interface State {
  list: any,
  currentSelect: any,
  cityList: any,
  actShow: false,
  show: false,
  storeCode: '',
  details: {},
  pIdData: {},
  jihuasuanId: '',
  pMobile: '',
  ppMobile: '',
  mobile: '',
  pUnionId: '',
  ppUnionId: '',
  authInfo: {},
  orderRecords: [],
  pUser: {
    mobile: '',
    avatarUrl: '',
    userId: '',
    nickname: ''
  },
  activityInfo: {
    viewTimes: 0,
    orderTimes: 0,
    shareTimes: 0
  },
  thirdPartyShareSource: ''
}

export default class CheapIndex extends Component<any, any> {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    this.state = {
      list: [],
      cityList: [],
      currentSelect: {},
      actShow: false,
      show: false,
      storeCode: '',
      details: {},
      pIdData: {},
      jihuasuanId: '',
      pMobile: '',
      ppMobile: '',
      mobile: '',
      pUnionId: '',
      ppUnionId: '',
      authInfo: {},
      orderRecords: [],
      pUser: {
        mobile: '',
        avatarUrl: '',
        userId: '',
        nickname: ''
      },
      activityInfo: {
        viewTimes: 0,
        orderTimes: 0,
        shareTimes: 0
      },
      thirdPartyShareSource: ''
    }
  }

  state: State

  async componentDidMount() {
    let {
      id,
      pMobile,
      ppMobile,
      pUnionId,
      ppUnionId,
      storeCode,
      thirdPartyShareSource
    } = this.$instance.router.params
    const USERINFO = Taro.getStorageSync('IS_USERINFO')
    if (pMobile) {
      this.getpMobileInfo(pMobile)
    }
    this.setState({
      id,
      pMobile,
      ppMobile,
      pUnionId,
      ppUnionId,
      storeCode,
      jihuasuanId: id,
      thirdPartyShareSource
    }, () => {
      this.getActivityView(id)
    })
  }

  /**
  * 获取一阶分销人的信息
  **/
  async getpMobileInfo(mobile) {
    const USERINFO = Taro.getStorageSync('IS_USERINFO')
    if (USERINFO.mobile == mobile) return
    Taro.showLoading({
      title: '加载中...',
      mask: true
    })
    getpMobileInfo({
      mobile
    }).then(res => {
      let pUser = res.data.data
      this.setState({
        pUser
      })
    }).finally(() => {
      Taro.hideLoading()
    })
  }

  /**
   * 活动规则
   **/
  gotoRule = () => {
    let {
      id
    } = this.$instance.router.params
    let query = {
      jihuasuanId: id
    }
    Taro.navigateTo({ url: `/pages/webview/index/index?path=/cheap/activity-rule&query=${JSON.stringify(query)}` })
  }

  gotoActivity() {
    Taro.navigateTo({
      url: '/pages/cheap/activity/index'
    })
  }

  // 活动详情
  getActivityView(id) {
    const USERINFO = Taro.getStorageSync('IS_USERINFO')
    let { pMobile, ppMobile, pUnionId, ppUnionId, thirdPartyShareSource } = this.state
    Taro.showLoading({
      title: '加载中...',
      mask: true
    })
    getCheapView({
      id
    }).then(res => {
      Taro.hideLoading()
      let details = res.data.data
      console.log('详情数据', details)
      try {
        // 支付宝不支持font标签
        if (process.env.TARO_ENV !== 'weapp') {
          details.rule = details.rule.replace(/<font/g, '<span').replace(/<\/font/g, '</span')
        }
      } catch (err) { }

      let orderRecords = details.orderRecords
      let activityInfo = details.activityInfo
      if (USERINFO && USERINFO.mobile) {
        updateViewLog({
          jihuasuanId: id,
          mobile: USERINFO.mobile,
          jihuasuanGoodsId: details.goods[0].id,
          pMobile: pMobile || '',
          ppMobile: ppMobile || '',
          pUnionId: pUnionId || '',
          ppUnionId: ppUnionId || '',
          thirdPartyShareSource: thirdPartyShareSource || ''
        })
      }
      this.setState({
        orderRecords,
        details,
        activityInfo,
        list: details.goods
      })
    })
  }

  onShareAppMessage(res) {
    console.log('res', res)
    const USERINFO = Taro.getStorageSync('IS_USERINFO')
    let { list, details, pMobile, pUnionId, ppUnionId, thirdPartyShareSource } = this.state
    if (res.from == 'button') { // 来自页面按钮的转发
      let paraams = {
        jihuasuanId: details.id,
        mobile: USERINFO.mobile,
        pMobile: pMobile,
        pUnionId: pUnionId,
        jihuasuanGoodsId: res.target.id,
        thirdPartyShareSource: thirdPartyShareSource || ''
      }
      updateShareLog(paraams)
      return {
        title: details.shareHeaderTitle || `养车超低价，分享赚佣金`,
        path: `pages/cheap/index/index?jihuasuanId=${list[0].jihuasuanId}&pMobile=${USERINFO.mobile}&ppMobile=${pMobile}&ppUnionId=${pUnionId}${thirdPartyShareSource ? `&thirdPartyShareSource=${thirdPartyShareSource}` : ''}`,
        imageUrl: details.upload6Url,
        bgImgUrl: details.upload6Url,
      }
    } else {
      let paraams = {
        jihuasuanId: list[0].jihuasuanId,
        mobile: USERINFO.mobile,
        pMobile: details.pMobile || '',
        pUnionId: pUnionId || '',
        thirdPartyShareSource: thirdPartyShareSource || ''
      }
      updateShareLog(paraams)
      return {
        title: details.shareHeaderTitle || `养车超低价，分享赚佣金`,
        path: `pages/cheap/index/index?jihuasuanId=${list[0].jihuasuanId}&pMobile=${USERINFO.mobile}&ppMobile=${pMobile}&ppUnionId=${pUnionId}${thirdPartyShareSource ? `&thirdPartyShareSource=${thirdPartyShareSource}` : ''}`,
        imageUrl: details.upload6Url,
        bgImgUrl: details.upload6Url,
      }
    }

  }



  render() {
    const { orderRecords, list, details, pMobile, ppMobile, pUnionId, ppUnionId, id, pUser, activityInfo, storeCode, thirdPartyShareSource } = this.state
    let alipayNode = []
    if (details && details.rule) {
      parse(details.rule, (err, nodes) => {
        console.log('err', err)
        if (!err) {
          alipayNode = nodes
          console.log(alipayNode)
        }
      })
    }
    console.log('details.upload4Url', details.upload4Url)
    return (
      <View className="topic-index">
        <View className="topic-rule"
          onClick={this.gotoRule}>活动规则
        </View>

        <View className="module-warp">
          <View className="bgfff">
            {
              list.map(item => {
                item.jihuasuanId = details.id
                return (
                  <View className="box-item">
                    <GoodsItem shareData={{
                      pMobile,
                      ppMobile,
                      pUnionId,
                      ppUnionId,
                      storeCode,
                      shareImg: details.upload6Url,
                      thirdPartyShareSource
                    }} goods={item}
                      detailsImg={details.upload4Url}></GoodsItem>
                  </View>
                )
              })
            }
          </View>

        </View>
        <View className="block">
          <View className="data">
            <View className="data-item">
              <View className="n">{activityInfo.viewTimes}</View>
              <View className="v"><Text className="icon icon-1"></Text>已浏览(次)</View>
            </View>
            <View className="data-item">
              <View className="n">{activityInfo.orderTimes}</View>
              <View className="v"><Text className="icon icon-2"></Text>已购买(人)</View>
            </View>
            <View className="data-item">
              <View className="n">{activityInfo.shareTimes}</View>
              <View className="v"><Text className="icon icon-3"></Text>已分享(次)</View>
            </View>
          </View>
        </View>

        {
          pMobile && pUser.nickname &&
          <View className="block">
            <View className="share-warp">
              <Image src="https://static3.jekunauto.com/img/cheap/top_pic_5.png"
                alt=""
                mode="widthFix"
                className="img pic-5" />
              <View className="title">
                <View>
                  <Image mode="widthFix" src="https://static3.jekunauto.com/img/cheap/t_4.png" alt="" className='record-ico' /> 来自<Text className="record-name">{pUser.nickname}</Text>的推荐
                </View>
              </View>
              <View className="sw-user">

                <View className="sw-user-l">
                  {
                    pUser.avatarUrl ? <Image mode="widthFix" src={pUser.avatarUrl}
                      alt="" className='img' /> : <Image mode="widthFix" src="https://static3.jekunauto.com/img/others/default_head.png"
                        alt="" className='img' />
                  }

                </View>
                <View className="sw-user-r"><Image mode="widthFix" src="https://static3.jekunauto.com/img/cheap/top_pic_4.png"
                  alt=""
                  className="img pic-3" />
                </View>
              </View>
            </View>
          </View>
        }

        {
          orderRecords.length !== 0 &&
          <View className="block">
            <View className="record">
              <View className="title">
                <View>

                  <Image mode="widthFix" src="https://static3.jekunauto.com/img/cheap/t_4.png" alt="" className='record-ico' />
                  最近购买
                </View>
                <View v-if="pMobile">
                  已有<Text className="t-r">{activityInfo.orderTimes}</Text>人购买
                </View>

              </View>
              <View className="r-item-warp">
                {
                  orderRecords.map((item, index) => {
                    return <View className="r-item" key={index}>
                      <View className="r-head">
                        {
                          item.avatarUrl ? <Image mode="widthFix" className='img' src={item.avatarUrl}
                            alt="" /> : <Image mode="widthFix" className='img' src="https://static3.jekunauto.com/img/others/default_head.png"
                              alt="" />
                        }
                      </View>
                      <View className="middle"><Text className="name">{item.name}</Text><Text className="i">{item.title}</Text></View>
                      <View className="t">{item.date}</View>
                    </View>
                  })

                }
              </View>

            </View>
          </View>
        }

        {details.rule && <View className="block">
          <View className="shop">
            <View className="title">
              <View>
                <Image mode="widthFix" src="https://static3.jekunauto.com/img/cheap/t_9.png" alt="" className='kown-ico1' />
                使用说明</View>
            </View>
            <View className="notice">
              {
                process.env.TARO_ENV === 'weapp' ? <RichText nodes={details.rule} /> : <RichText nodes={alipayNode} />
              }

            </View>
          </View>
        </View>
        }


        <View className="block">
          <View className="pic-warp">
            <View className="pic-warp-title">好物不能独享，赶紧分享给好友哦~</View>
            <Image mode="widthFix" src="https://static3.jekunauto.com/img/cheap/topic_rule.png"
              alt="" className='img' />
          </View>
        </View>

      </View>
    )
  }
}
